package com.heima.common.jackson;

import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.heima.model.common.annotation.IdEncrypt;

import java.util.ArrayList;
import java.util.List;

public class ConfusionSerializerModifier extends BeanSerializerModifier {

    @Override
    public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
                                                     BeanDescription beanDesc,
                                                     List<BeanPropertyWriter> beanProperties) {
        List<BeanPropertyWriter> newWriter = new ArrayList<>();
        for (BeanPropertyWriter writer : beanProperties) {
            String name = writer.getType().getTypeName();
            if (null == writer.getAnnotation(IdEncrypt.class)
                    && !writer.getName().equalsIgnoreCase("id")) {
                newWriter.add(writer); // 不是id字段，且没有加IdEncrypt注解, 不处理
            } else {
                writer.assignSerializer(new ConfusionSerializer()); // 加密字段绑定序列化器
                newWriter.add(writer);
            }
        }
        return newWriter;
    }
}
